package com.captain.lc.lru;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Des:
 *
 * @author XL
 * @Date 2021/10/12 9:40
 */
public class SimpleCache<K, V> implements Cache<K, V> {

    private final Map<K, V> cache;

    public SimpleCache(int size) {
        cache = new HashMap<> (size);
    }

    @Override
    public void put(K key, V val) {
        cache.put(key, val);
    }

    @Override
    public V get(K key) {
        return cache.get(key);
    }

    @Override
    public V get(K key, Callable<? extends V> call) throws Exception {
        if (cache.containsKey(key)) {
            return cache.get(key);
        } else {
            V v2 = call.call();
            cache.put(key, v2);
            return v2;
        }
    }

    @Override
    public V remove(K key) {
        return cache.remove(key);
    }

    @Override
    public void clear() {
        cache.clear();
    }

    @Override
    public int getSize() {
        return cache.size();
    }
}
